package com.bawei.module_moto_circle.ui.search

import androidx.lifecycle.viewModelScope
import com.bawei.lib_common.base.BaseViewModel
import com.bawei.lib_common.base.state.Empty
import com.bawei.lib_common.base.state.Failed
import com.bawei.lib_common.base.state.Loading
import com.bawei.lib_common.base.state.RequestEvent
import com.bawei.lib_common.base.state.Success
import com.bawei.lib_storage.mmkv.AppMMKV
import com.bawei.lib_storage.mmkv.utils.Gson
import com.bawei.module_moto_circle.model.SearchKeywordModelItem
import com.bawei.module_moto_circle.model.Topic
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 *作者：lxy
 *功能:
 *时间：2025/6/4
 */
@HiltViewModel
class SearchViewModel @Inject constructor(private val mRepository: SearchRepository) :
    BaseViewModel() {

    //搜索关键词
    val mKeywords = MutableStateFlow("")

    private var requestHotTopicsEvent_ = MutableSharedFlow<RequestEvent>()
    val requestHotTopicsEvent = requestHotTopicsEvent_.asSharedFlow()

    private var _searchSuggestionEvent = MutableSharedFlow<RequestEvent>()
    val mSearchSuggestionEvent = _searchSuggestionEvent.asSharedFlow()

    var mHotTopics = listOf<Topic>()
    var mInformation = listOf<Topic>()
    var mSuggestionList = mutableListOf<SearchKeywordModelItem>()
    fun clearKeyword() {
        mKeywords.value = ""
    }


    fun hotTopics() {
        execute(
            action = mRepository.hotTopics(),
            onStart = {
                requestHotTopicsEvent_.emit(Loading)
            },
            onError = {
                requestHotTopicsEvent_.emit(Failed(it))
            },
            onFinish = {
                if (it.data!=null){
                    if (!it.data.topicList.isNullOrEmpty()){
                        mHotTopics = it.data.topicList!!.map { topics->
                            Topic(topics.topicId,topics.topicName)
                        }
                    }
                    if (!it.data.informationList.isNullOrEmpty()){
                        mInformation = it.data.informationList!!.map {information->
                            Topic(information.topicId,information.topicName)
                        }
                    }
                }
                requestHotTopicsEvent_.emit(Success)
            }
        )
    }

    fun isHistoryEmpty(): Boolean {
        return (Gson.fromJson<List<String>>(AppMMKV.searchHistory) ?: listOf()).isEmpty()
    }

    fun searchKeywordList(){
        viewModelScope.launch (Dispatchers.IO){
            //用户300ms无操作的时候发起网络请求，上一次请求还未结束取消上一次网络请求
            mKeywords.debounce(300)
                .filter { it.isNotBlank() }
                .collectLatest {
                    execute(
                        action = mRepository.searchKeywordList(it),
                        onStart = {
                            _searchSuggestionEvent.emit(Loading)
                        },
                        onError = {
                            _searchSuggestionEvent.emit(Failed(it))
                        },
                        onFinish = {
                            if (!it.data.isNullOrEmpty()){
                                mSuggestionList.clear()
                                mSuggestionList.addAll(it.data)
                                _searchSuggestionEvent.emit(Success)
                            }else{
                                mSuggestionList.clear()
                                _searchSuggestionEvent.emit(Failed("暂无数据内容"))
                            }
                        }
                    )
                }
        }
    }
}